package com.atguigu.datastream.test.day06;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;

/**
 * ClassName: Flink04_ProcessFun_WordCount
 * Package: com.atguigu.test.day06
 * Description:
 *              process实现wc
 * @Author ChenJun
 * @Create 2023/4/13 9:37
 * @Version 1.0
 */
public class Flink04_ProcessFun_WordCount {
    public static void main(String[] args) throws Exception {

        //1. 创建流的实例
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3. 将数据转换为JavaBean
        SingleOutputStreamOperator<String> wordCount = streamSource.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String value, ProcessFunction<String, String>.Context ctx, Collector<String> out) throws Exception {
                String[] split = value.split(" ");
                for (String s : split) {
                    out.collect(s);
                }
            }
        });

        //4. 将单词转换为二元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOne = wordCount.process(new ProcessFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void processElement(String value, ProcessFunction<String, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                out.collect(Tuple2.of(value, 1));
            }
        });

        //5. 将相同的key聚合到一起
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordCount1 =
                wordToOne.process(new ProcessFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
                    HashMap<String, Integer> hashMap = new HashMap<>();
            @Override
            public void processElement(Tuple2<String, Integer> value, ProcessFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {


                //1判断是否有相同的key
                if (hashMap.containsKey(value.f0)) {
                    Integer integer = hashMap.get(value.f0);
                    integer += 1;
                    hashMap.put(value.f0, integer);
                } else {
                    hashMap.put(value.f0, 1);
                }
                out.collect(Tuple2.of(value.f0, hashMap.get(value.f0)));
            }
        });

        wordCount1.print();
       env.execute();

    }
}
